package com.android.monee.view.activity;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.monee.binding.binder.Abstract1WBinder;
import com.android.monee.data.access.DaoListener;
import com.android.monee.data.access.SimpleDaoListener;
import com.android.monee.data.model.Budget;
import com.android.monee.data.model.Budget.BudgetState;
import com.android.monee.data.model.Mensuality;
import com.android.monee.domain.BudgetService;
import com.android.monee.domain.MensualityService;
import com.android.monee.view.model.BudgetOverview;
import com.android.monee.R;


public class OverviewSectionFragment extends Fragment {

	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";

	private View root;
	private BudgetOverviewCustomAdapter listAdapter;
	private Resources res;
	private DaoListener<Budget, Integer> budgetDaoListener;
	private DaoListener<Mensuality, Integer> mensualityDaoListener;
	
	public OverviewSectionFragment() {
		this.setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		this.root = inflater.inflate(R.layout.page_overview, container,
				false);

		this.res = getResources();
		
		updateView();
		
		this.budgetDaoListener = new DaoListener<Budget, Integer>() {
			@Override
			public void onInsert(Budget obj) {		
				listAdapter.add(new BudgetOverview(obj, res));
				listAdapter.notifyDataSetChanged();
			}

			@Override
			public void onUpdate(Budget obj) {
				//TODO : on peut optimiser en cherchant le BudgetOverview correspondant 
				//à obj juste modifié et en recopiant les données de obj vers le bon budgetOverview 
				//On réutilisera alors le binding pr maj de l'ui
				updateView();
			}

			@Override
			public void onDelete(Integer id) {
				listAdapter.remove(id);
				listAdapter.notifyDataSetChanged();
			}			
		};

		BudgetService.addBudgetDaoListener(this.budgetDaoListener);
		
		this.mensualityDaoListener = new SimpleDaoListener<Mensuality, Integer>() {
			@Override
			public void onChange() {
				updateView();
			}
		};
		
		MensualityService.addBudgetDaoListener(this.mensualityDaoListener);
		return this.root;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
		inflater.inflate(R.menu.overview, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()){
			case R.id.overview_reload:
				updateView();
		}
		
		return true;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterContextMenuInfo infos = (AdapterContextMenuInfo) menuInfo;
		BudgetOverview budgetOverview  = (BudgetOverview) infos.targetView.getTag();
		
		menu.setHeaderTitle(budgetOverview.getName());

		MenuInflater inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.budget_overview_ctx, menu);	
		
		if(budgetOverview.getState() == BudgetState.RUNNING){
			menu.findItem(R.id.budget_overview_ctx_resume).setVisible(false);
			menu.findItem(R.id.budget_overview_ctx_pause).setVisible(true);
		}
		else if(budgetOverview.getState() == BudgetState.PAUSED){
			menu.findItem(R.id.budget_overview_ctx_pause).setVisible(false);
			menu.findItem(R.id.budget_overview_ctx_resume).setVisible(true);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		BudgetOverview budgetOverview  = (BudgetOverview) menuInfo.targetView.getTag();
		
		switch(item.getItemId()){
		case R.id.budget_overview_ctx_open:
			OverviewSectionFragment.openBudgetdetailsActivity(getActivity(), budgetOverview.getId());
			return true;
		case R.id.budget_overview_ctx_pause:
			budgetOverview.setState(BudgetState.PAUSED);
			BudgetService.update(budgetOverview);
			return true;
		case R.id.budget_overview_ctx_resume:
			budgetOverview.setState(BudgetState.RUNNING);
			BudgetService.update(budgetOverview);
			return true;
		case R.id.budget_overview_ctx_delete:
			//TODO : popup etes-vous sur ?
			BudgetService.delete(budgetOverview);
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	
	private void updateView (){
		
		List<BudgetOverview> allBudgets = BudgetOverview.newCollection(
				BudgetService.findAll(), getResources());

		this.listAdapter = new BudgetOverviewCustomAdapter(getActivity(),
				R.layout.fragment_budget_overview, allBudgets);
		
		ListView listView = (ListView) this.root.findViewById(R.id.budget_list);
		listView.setAdapter(this.listAdapter);
		this.registerForContextMenu(listView);
		//Tip : chaque élément dans la ListView doit être longClickable !
		
		TextView totProvTV = (TextView) this.root.findViewById(R.id.tot_prov);
		TextView totMensTV = (TextView) this.root.findViewById(R.id.tot_mens);

		totProvTV.setText(BudgetOverview.getTotalProvAmountLib(allBudgets, getResources()));
		
		//TODO : virer cela ca ne veut plus trop dire grand chose...
		totMensTV.setText(BudgetOverview.getTotalMensAmountLib(allBudgets, getResources()));
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		this.root = null;
		this.listAdapter = null;
		this.res = null;
		BudgetService.deleteBudgetDaoListener(this.budgetDaoListener);
		this.budgetDaoListener = null;
	}

	public static void openBudgetdetailsActivity(Context ctx, int budgetId){
		Intent intent = new Intent(ctx, BudgetsActivity.class);
		intent.putExtra(BudgetsActivity.CURRENT_BUDGET_ID_FOR_OPEN, budgetId);
		ctx.startActivity(intent);
	}
}

class BudgetOverviewCustomAdapter extends ArrayAdapter<BudgetOverview> {

	private int resource;
	private LayoutInflater inflater;
	private List<BudgetOverview> budgets;

	public BudgetOverviewCustomAdapter(Context context, int resourceId,
			List<BudgetOverview> objects) {
		super(context, resourceId, objects);
	
		this.resource = resourceId;
		this.inflater = LayoutInflater.from(context);
		this.budgets = objects;
	}

	//TODO : à quoi cela sert ? registerDataSetObserver(DataSetObserver observer)
	public View getView(int position, View budgetOverviewView, ViewGroup parent) {

		budgetOverviewView = (RelativeLayout) inflater.inflate(resource, null);

		ImageView stateIV = (ImageView) budgetOverviewView.findViewById(R.id.icon_budget_state);
		TextView libTV = (TextView) budgetOverviewView.findViewById(R.id.lib_budget);
		TextView libMtnProvTV = (TextView) budgetOverviewView
				.findViewById(R.id.mtn_prov);
		TextView libMtnMensTV = (TextView) budgetOverviewView
				.findViewById(R.id.mtn_mens);
		ProgressBar progressBar = (ProgressBar) budgetOverviewView
				.findViewById(R.id.progress);
		View progressSpacer = budgetOverviewView.findViewById(R.id.progress_spacer);

		BudgetOverview budgetOverview = getItem(position);

		final Resources res = parent.getResources();
		new Abstract1WBinder<BudgetOverview, BudgetOverview, BudgetOverview.State, ImageView, BudgetState>(budgetOverview, budgetOverview.new State(), stateIV) {
			@Override
			public void updateTarget(ImageView target, BudgetState value) {
				if(value == BudgetState.RUNNING)
					target.setImageDrawable(res.getDrawable(android.R.drawable.ic_media_play));
				else if(value == BudgetState.PAUSED)
					target.setImageDrawable(res.getDrawable(android.R.drawable.ic_media_pause));
			}
		};
		
		libTV.setText(budgetOverview.getName());

		libMtnProvTV.setText(budgetOverview.getAmmountTotProvLib());
		libMtnMensTV.setText(budgetOverview.getAmountMensLib());
		
		progressBar.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
				0));
		progressBar.setMax(budgetOverview.getTotalAmountFloat().intValue());
		progressBar.setProgress(budgetOverview.getProvAmountFloat().intValue());
		
		progressSpacer.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
				1));
		/*progressBar.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
				budgetOverview.getProgressBarWeight()));
		progressSpacer.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
				budgetOverview.getProgressSpacerWeight()));*/

		RelativeLayout budgetWidget = (RelativeLayout) budgetOverviewView
				.findViewById(R.id.budget_overview_widget);
		budgetWidget.setTag(budgetOverview);
		
		budgetWidget.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				BudgetOverview budget = (BudgetOverview) view.getTag();
				OverviewSectionFragment.openBudgetdetailsActivity(getContext(), budget.getId());
			}
		});
		return budgetOverviewView;
	}
	
	public void remove (Integer id){
		for (BudgetOverview budget : budgets){
			if(budget.getId() == id){
				this.budgets.remove(budget);
				return;				
			}
		}
	}
}
